package fa7.socialcode.dao.hibernate;

import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import fa7.socialcode.dao.NoticiaDao;
import fa7.socialcode.model.Noticia;

@Repository(value = "noticiaDao")
public class NoticiaDaoHibernate implements NoticiaDao {

	HibernateTemplate hibernateTemplate;
	// Somente para log
	Log logger = LogFactory.getLog(NoticiaDaoHibernate.class);

	@Autowired
	public NoticiaDaoHibernate(SessionFactory sessionFactory) {
		this.hibernateTemplate = new HibernateTemplate(sessionFactory);
	}

	public void removeNoticia(Long id) {
		hibernateTemplate.delete(findNoticia(id));
	}

	public void saveNoticia(Noticia noticia) {
		hibernateTemplate.merge(noticia);
		if (logger.isDebugEnabled()) {
			logger.debug("noticiaId set to: " + noticia.getId());
		}
	}

	public Noticia findNoticia(Long id) {
		Noticia noticia = (Noticia) hibernateTemplate.get(Noticia.class, id);
		if (noticia == null) {
			throw new ObjectRetrievalFailureException(Noticia.class, id);
		}
		return noticia;
	}

	public void removeNoticia(Noticia noticia) {
		hibernateTemplate.delete(noticia);
	}

	public List findNoticias() {
		return hibernateTemplate.find("from Noticia");
	}

	@Override
	public List findNoticiasByDate() {
		Object[] params = { new Date(), new Date() };
		List noticias = hibernateTemplate.find(
				"from Noticia n where n.dataInicial < ? and n.dataFinal > ?",
				params);
		return noticias;
	}

	@Override
	public Date findDataPostagemById(Long id) {
		Noticia n = (Noticia) hibernateTemplate.find(
				"from Noticia n where n.id=?", id).get(0);

		return n.getDataPostagem();
	}

	@Override
	public Noticia findNoticiaByDate(Long noticiaId) {
		Noticia noticia = (Noticia) hibernateTemplate.get(Noticia.class,
				noticiaId);
		if (noticia == null) {
			throw new ObjectRetrievalFailureException(Noticia.class, noticiaId);
		}
		return noticia;
	}

}